# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : control_editor.py
# Date      : 2018/11/6
# IDE       : PyCharm
# Version   : 1.0.1
# -------------------------------


__author__ = "lin lingwei"
__version__ = "1.1.2"

import os, sys, json

import maya.cmds as mc

import configs.constants.global_constant as gc

import scripts.commonCmds as cCore
import editors.editor as wCore
import scripts.curveCmds as crvCore

reload(crvCore)



class ControlEditor(wCore.Editor):
    def __init__(self):
        super(ControlEditor,self).__init__()
        self.radio = "radioCollection"
        self.colorPort = "colorPort"
    
    def editor(self):
        
        winName = "ControlEditor"
        winTitle = " - Control Eidtor - V{}".format(__version__)
        image = os.path.join(gc.gIconPath,"mainLogo.svg")
        
        self.isExist(winName)
        _win = mc.window(winName, t=winTitle, wh=[400, 400], s=False, mxb=False, te=100, )
        
        self.mainMenu()
        self.mainLayout()
        
        mc.showWindow(_win)
        return
    
    def mainMenu(self):
        mbl = mc.menuBarLayout(bgc=self.rgbConvert(118, 137, 143))
        mc.menu(l='File')
        mc.menuItem(l="Export ...", c=lambda *args: self.btn_export())
        # mc.menuItem(divider=True)
        # mc.menuItem(l="Open Path",c=lambda *args:self.btn_openPath())
        
        mc.menu(l='About')
        mc.menuItem(l="Version ...")
        
        return
    
    def mainLayout(self):
        
        form = mc.formLayout(bgc=self.rgbConvert(157, 181, 193))
        
        iconLay = self.iconLayout()
        cmdLay = self.cmdlistLayout()
        colorLay = mc.button("Change Color", bgc=self.rgbConvert(87, 152, 184), h=30,
                             c=lambda *args: self.btn_changeColor())
        ver = self.copyright()
        mc.formLayout(form, edit=True,
                      attachForm=[(iconLay, 'top', 5), (iconLay, 'left', 5),
                                  (cmdLay, 'top', 5), (cmdLay, 'right', 5),
                                  (colorLay, 'right', 5),
                                  (ver, 'bottom', 5), (ver, 'right', 5), (ver, 'left', 5)],
                      attachControl=[(colorLay, 'left', 5, iconLay), (cmdLay, 'left', 5, iconLay),
                                     (iconLay, 'bottom', 5, ver), (colorLay, 'bottom', 5, ver),
                                     ],
        
                      attachPosition=[(iconLay, 'right', 5, 75), (cmdLay, 'left', 0, 75)],
                      # attachNone=(b2, 'top')
                      )
        return form
    
    def iconLayout(self):
        
        form = mc.formLayout(bgc=self.rgbConvert(118, 137, 143))
        
        row = mc.rowLayout(nc=10, bgc=self.rgbConvert(118, 137, 143), ebg=True)
        collection1 = mc.radioCollection(self.radio)
        rb1 = mc.radioButton("create", label=' Create ', sl=True)
        rb2 = mc.radioButton("add", label=' Add    ')
        rb3 = mc.radioButton("replace", label=' Replace')
        mc.setParent('..')
        
        iconList = os.listdir(crvCore.controlIcon)
        
        column = mc.columnLayout(adj=True, bgc=self.rgbConvert(54, 56, 58))
        iconGrid = mc.gridLayout(cwh=[57, 57], nbg=True, bgc=self.rgbConvert(54, 56, 58), ebg=True,
                                 aec=True, nc=5)
        for icon in iconList:
            imagePath = os.path.join(crvCore.controlIcon, icon)
            self.iconButton(icon, imagePath)
        
        mc.setParent('..')
        mc.setParent('..')
        colorPort = mc.palettePort(self.colorPort, dimensions=(16, 2), ced=0, td=1, at=32, setCurCell=0)
        self.initPalette(colorPort)
        
        mc.setParent('..')
        
        mc.formLayout(form, edit=True,
                      attachForm=[(row, 'top', 0), (row, 'left', 0), (row, 'right', 0),
                                  (column, 'left', 0), (column, 'right', 0),
                                  (colorPort, 'left', 0), (colorPort, 'right', 0), (colorPort, 'bottom', 0),
                                  # (colorLay, 'right', 5),
                                  # (ver, 'bottom', 5), (ver, 'right', 5), (ver, 'left', 5)
                                  ],
                      attachControl=[
                          (column, 'top', 5, row),
                          (colorPort, 'top', 5, column),
                          # (iconGrid, 'bottom', 5, color),
                      ],
        
                      attachPosition=[(colorPort, 'top', 5, 90), (column, 'bottom', 0, 90)],
                      # attachNone=(b2, 'top')
                      )
        
        return form
    
    def initPalette(self, palettePort):
        if mc.palettePort(palettePort, ex=True):
            for i in range(0, 31):
                if i == 0:
                    mc.palettePort(palettePort, e=True, t=0)
                else:
                    r, g, b = mc.colorIndex(i, q=True)
                    mc.palettePort(palettePort, e=True, r=True, rgb=(i, r, g, b))
        
        mc.palettePort(palettePort, e=1, scc=5, )
    
    def iconButton(self, icon, imagePath):
        
        iconName = os.path.splitext(icon)[0]
        
        mc.iconTextButton(l=iconName, i=imagePath, mw=2, mh=2, c=lambda *args: self.btn_iconControl(iconName),
                          bgc=self.rgbConvert(54, 56, 58), ebg=True)
        
        return
    
    def cmdlistLayout(self):
        column = mc.columnLayout(adj=True, bgc=self.rgbConvert(54, 56, 58))
        
        scGrp = "shapeScale"
        mc.floatSliderGrp(scGrp, field=True, cw2=[35, 2], fmx=1.5, fmn=0.5, max=1.5, min=0.5, v=1,
                          cc=lambda *args: self.btn_shapeScaleChangeCmd(scGrp))
        mc.separator(h=4)
        
        mc.rowLayout(nc=10)
        collection1 = mc.radioCollection()
        rb1 = mc.radioButton("x", label='X', sl=True)
        rb2 = mc.radioButton("y", label='Y')
        rb3 = mc.radioButton("z", label='Z')
        mc.setParent("..")
        
        mc.button("mirrorShape", l="Mirror", c=lambda *args: self.btn_mirror(collection1))
        
        mc.separator()
        mc.button("export control set", c=lambda *args: self.btn_exportControlSet())
        mc.button("import control set", c=lambda *args: self.btn_importControlSet())
        
        mc.setParent('..')
        
        return column
    
    def btn_iconControl(self, controlName):
        
        colorIndex = mc.palettePort(self.colorPort, q=True, scc=True)
        
        # if colorIndex > 23: colorIndex -= 1
        # if colorIndex == 23: colorIndex = 18
        
        # print(colorIndex)
        
        mode = mc.radioCollection(self.radio, q=True, sl=True)
        if mode == "create":
            crvCore.createControl(controlName, controlName, colorIndex)
        elif mode == "add":
            sel = mc.ls(sl=True)
            if sel:
                for sl in sel:
                    crvCore.addShape(sl, controlName, colorIndex)
        elif mode == "replace":
            sel = mc.ls(sl=True)
            if sel:
                for sl in sel:
                    crvCore.replaceShape(sl, controlName, colorIndex)
        
        return
    
    def btn_export(self):
        sel = mc.ls(sl=True)
        
        # print(fpath,fname)
        
        if sel:
            isShape = mc.listRelatives(sel[0], s=True)
            if isShape:
                if mc.nodeType(isShape[0]) == "nurbsCurve":
                    fp = mc.fileDialog2(dir=crvCore.controlData, fileFilter="Curve Data (*.crvData);;")[0]
                    fpath, fname = os.path.split(fp)
                    crvCore.exportData(sel[0], fpath, fname)
        #         else:
        #             cCore.lw_warnings("It's no nurbsCurve.")
        #     else:
        #         cCore.lw_warnings("{} no shape.".format(sel[0]))
        # else:
        #     cCore.lw_warnings("Please select nurbsCurve.")
        
        return
    
    def btn_exportControlSet(self):
        
        sel = mc.ls("*_ctrl", fl=True)
        
        data = {}
        for sl in sel:
            data[sl] = crvCore.getData(sl)
        
        with open(os.path.join("D:/", "t.json"), "w") as fp:
            json.dump(data, fp, sort_keys=True, indent=4, separators=(',', ': '))
            # fp.write(data)
        
        return
    
    def btn_importControlSet(self):
        
        with open(os.path.join("D:/", "t.json"), "r") as fp:
            data = json.load(fp)
        
        for d in data:
            try:
                crvCore.setData(d, data[d])
            except:
                print d
        
        return
    
    def btn_openPath(self):
        
        return
    
    def btn_changeColor(self):
        sel = mc.ls(sl=True)
        if sel:
            colorIndex = mc.palettePort(self.colorPort, q=True, scc=True)
            for sl in sel:
                crvCore.changColor(sl, colorIndex)
        return
    
    def btn_shapeScaleChangeCmd(self, fg):
        
        sel = mc.ls(sl=True)
        if not sel:
            return
        
        scValue = mc.floatSliderGrp(fg, q=True, v=True)
        
        try:
            for sl in sel:
                shape = cCore.findRelatedShape(sl)
                if mc.nodeType(shape) == "nurbsCurve":
                    crvCore.scaleXYZ(sl, scValue)
        finally:
            mc.floatSliderGrp(fg, e=True, v=1)
        return
    
    def btn_mirror(self, cg):
        
        sel = mc.ls(sl=True)
        csl = mc.radioCollection(cg, q=True, sl=True)
        
        if sel:
            if len(sel) > 2:
                return
            elif len(sel) == 2:
                otherSide = sel[1]
            else:
                otherSide = sel[0].replace("L_", "R_")
            
            crvCore.mirrorShape(sel[0], otherSide, csl)
        else:
            all_left = mc.ls("L_*_ctrl")
            # print all_left
            for al in all_left:
                otherSide = al.replace("L_", "R_")
                crvCore.mirrorShape(al, otherSide, csl)
        
        return


def showEditor():
    ControlEditor().editor()
    return


if __name__ == '__main__':
    pass